<route lang="json5">
{
  meta: {
    auth: true,
    label: '触底加载',
  },
}
</route>

<template>
  <div ref="boxRef" class="h-full overflow-y-scroll">
    <div
      class="grid gap-4"
      :style="{
        gridTemplateColumns: `repeat(${boxColumns},  1fr)`,
      }"
    >
      <a-card class="w-full h-full" :title="item.name" v-for="item in dataList">
        <template #extra>
          <a-link>{{ item.ip }}</a-link>
        </template>
        <div class="flex flex-col">
          <span>{{ item.content }}</span>
          <span>{{ item.phone }}</span>
          <span>{{ item.time }}</span>
          <span>{{ item.id }}</span>
        </div>
      </a-card>

      <a-button :style="{ gridColumn: `span ${boxColumns}` }" v-if="isClose">没有更多了</a-button>
      <a-button :style="{ gridColumn: `span ${boxColumns}` }" v-else @click="onLoadMore">点击加载更多</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getMockList, type IGetMockList } from 'api/test1'
import { useInfiniteScroll } from 'hooks/useInfiniteScroll'

const size = 15
const boxRef = ref<HTMLElement>()
const dataList = ref<IGetMockList[]>([])
const LOAD_TIMES = ref(0) // 模拟最大页面控制暂停

const { width: clientW } = useElementSize(boxRef)
const boxColumns = computed(() => Math.floor(clientW.value / 270) || 1)

const { stop, isClose } = useInfiniteScroll(boxRef, onLoadMore, { distance: 20, direction: 'bottom', interval: 100 })

async function onLoadMore() {
  LOAD_TIMES.value += 1
  const start = dataList.value.length
  const { list } = await getMockList({ start, size })
  if (!list || list.length < size || LOAD_TIMES.value >= 3) {
    stop()
  }
  dataList.value.push(...list)
}
</script>
